package com.sdy.kzyy.pc.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.common.model.BizException;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.kzyy.biz.dto.StoreManageDTO;
import com.sdy.kzyy.biz.model.Area;
import com.sdy.kzyy.biz.model.Manager;
import com.sdy.kzyy.biz.service.AreaService;
import com.sdy.kzyy.biz.service.ManagerService;
import com.sdy.kzyy.biz.service.StoreInventoryService;
import com.sdy.kzyy.biz.service.StoreService;
import com.sdy.kzyy.pc.util.Constants;
import com.sdy.mvc.controller.BaseController;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cgj
 * @since 2020-03-25
 */
@Slf4j
@RestController
@SuppressWarnings("unchecked")
@RequestMapping("/storeManage")
@Api(tags = "药店管理相关接口")
public class StoreManageController extends BaseController {
    @Autowired
    private StoreService storeService;
    @Autowired
    private AreaService areaService;
    @Autowired
    private ManagerService managerService;

    @GetMapping("/getStoreManagePage")
    @ResponseBody
    @ApiOperation(value = "药店列表页", response = StoreManageDTO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "药店名")
    })
    public Response getStoreManagePage(HttpServletRequest request, String name, Page page) throws UnsupportedEncodingException, BizException {
        if (StringUtils.isNotBlank(name)) {
            name = URLDecoder.decode(name, "UTF-8");
        }
        Integer userId = getUserId(request, Constants.SESSION_WEB_USER_ID);
        Manager byId = managerService.getById(userId);
        Assert.isTrue(byId == null, "当前用户未登录!");
        List<StoreManageDTO> storeManagePage = storeService.getStoreManagePage(page, name, byId.getStoreCode());
        for (StoreManageDTO l : storeManagePage) {
            String area = l.getAreaName();
            String address = l.getAddress();
            if (StringUtils.isBlank(area)) {
                area = "";
            }
            if (StringUtils.isBlank(address)) {
                address = "";
            }
            l.setAreaAddress(area + address);
        }
        return Response.success(page.setRecords(storeManagePage));
    }

    @GetMapping("/downLodeStoreManage")
    @ResponseBody
    @ApiOperation(value = "导出", response = StoreManageDTO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "药店名")
    })
    public void downLodeStoreManage(String name, HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException, BizException {
        if (StringUtils.isNotBlank(name)) {
            name = URLDecoder.decode(name, "UTF-8");
        }
        Integer userId = getUserId(request, Constants.SESSION_WEB_USER_ID);
        Manager byId = managerService.getById(userId);
        Assert.isTrue(byId == null, "当前用户未登录!");
        List<StoreManageDTO> storeManagePage = storeService.getStoreManagePage(null, name, byId.getStoreCode());
        for (int i = 0; i < storeManagePage.size(); i++) {
            String week = storeManagePage.get(i).getWeek();
            String weekTime = storeManagePage.get(i).getWeekTime();
            if (week == null) {
                week = "";
            }
            if (weekTime == null) {
                weekTime = "";
            }
            storeManagePage.get(i).setWeekTimeDate(week + weekTime);
        }
        for (StoreManageDTO l : storeManagePage) {
            String area = l.getAreaName();
            String address = l.getAddress();
            if (StringUtils.isBlank(area)) {
                area = "";
            }
            if (StringUtils.isBlank(address)) {
                address = "";
            }
            l.setAreaAddress(area + address);
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
            String date = sdf.format(new Date());
            String fileName = "药店数据-" + date + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
            EasyExcel.write(response.getOutputStream(), StoreManageDTO.class).sheet("药店数据").doWrite(storeManagePage);
        } catch (Exception e) {
            log.error("药店数据" + e.getMessage(), e);
        }
    }

    @PostMapping("saveStorManage")
    @ApiOperation(value = "新增店铺数据", response = StoreManageDTO.class)
    public Response saveStorManage(@RequestBody @ApiParam(value = "storeManageDTO",name = "实体类") StoreManageDTO storeManageDTO) throws BizException {
        Boolean aBoolean = storeService.saveStorManage(storeManageDTO);
        Assert.notTrue(aBoolean, "新增数据出错!");
        return Response.success(aBoolean);
    }

    @GetMapping("/getStoreManageOne")
    @ResponseBody
    @ApiOperation(value = "修改前获取数据", response = StoreManageDTO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键")
    })
    public Response<StoreManageDTO> getStoreManageOne(Integer id) throws BizException {
        Assert.isTrue(id == null, "传入数据为空!");
        StoreManageDTO storeManageOne = storeService.getStoreManageOne(id);
        return Response.success(storeManageOne);
    }

    @PostMapping("updateStorManage")
    @ApiOperation(value = "修改店铺数据", response = StoreManageDTO.class)
    public Response updateStorManage(@RequestBody @ApiParam(value = "storeManageDTO",name = "实体类") StoreManageDTO storeManageDTO) throws BizException {
        Boolean aBoolean = storeService.updateStorManage(storeManageDTO);
        Assert.notTrue(aBoolean, "修改数据出错!");
        return Response.success(aBoolean);
    }

    @PostMapping("delStorManage")
    @ApiOperation(value = "删除店铺数据", response = StoreManageDTO.class)
    public Response<Boolean> delStorManage(@RequestBody @ApiParam(value = "map",name = "map(放入主键id & state(启用-1 禁用-2))")Map<String, Integer> map) throws BizException {
        Integer id = map.get("id");
        Assert.isNull(id, "传参错误!");
        Integer state = map.get("state");
        Assert.isNull(state, "传参错误!");
        Boolean aBoolean = storeService.delStorManage(id, state);
        Assert.notTrue(aBoolean, "删除失败!");
        return Response.success(aBoolean);
    }

    @GetMapping("/getAllArea")
    @ResponseBody
    @ApiOperation(value = "查询所有区县接口")
    public Response getAllArea() {
        List<Area> allArea = areaService.getAllArea();
        return Response.success(allArea);
    }

}
